/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ServerClient;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author TUAN ANH
 */
public class Server implements TranferData{
    private Socket receiveSocket; // socket 
    private ServerSocket serverSocket; // server
    private BufferedReader bufferedReader; // input stream
    private DataOutputStream dataOutputStream; // outputstream
    private int port;
//    String localhost;
    public Server(int port){
//        this.localhost = localhost;
        this.port = port;
    }
    @Override
    public void initConnection()  {
        try{
        this.serverSocket = new ServerSocket(port);
        System.out.println("waiting connect in port "+port);
        this.receiveSocket = serverSocket.accept();
        this.bufferedReader = new BufferedReader(new InputStreamReader(receiveSocket.getInputStream())); 
        this.dataOutputStream = new DataOutputStream(receiveSocket.getOutputStream());
        }catch(Exception ex){
            System.out.println(ex.toString());
        }
    }

    @Override
    public String receiveData(){
        try{
        String stringReceive = bufferedReader.readLine();
        return stringReceive;
        }catch(Exception ex){
            System.out.println(ex.toString());
            return null;
        }
    }

    @Override
    public void sentData(String data)  {
//        throw new UnsupportedOperationException("Not supported yet.");
        try{
        for(int i=0;i<data.length();i++){
            dataOutputStream.write((byte) data.charAt(i));
        }
        dataOutputStream.write(13);
        dataOutputStream.flush();
        }catch(Exception exc){
            System.out.println(exc.toString());
        }
    }

    @Override
    public void close() {
//        throw new UnsupportedOperationException("Not supported yet.");
        try{
        serverSocket.close();
        receiveSocket.close();
        bufferedReader.close();
        dataOutputStream.close();
        }catch(Exception ex){
            System.out.println(ex.toString());
        }
    }
    
    
}
